#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<unistd.h>
#include<linux/stat.h>
#include<string.h>

#define FIFO "PUBFIFO"
#define FIFO1 "PRIFIFO1"
#define FIFO2 "PRIFIFO2"

int main()
{
	FILE *fp;
	FILE *fp1;
	FILE *fp2;
	char readbuf[100];
	char writebuf[100];
	if((fp = fopen(FIFO,"r")) == NULL)
	{
		umask(0);
		mknod(FIFO,S_IFIFO|06666,0);
	}
	else
		fclose(fp);
	if((fp1 = fopen(FIFO1,"r")) == NULL)
    {
        umask(0);
        mknod(FIFO1,S_IFIFO|06666,0);
    }
    else
        fclose(fp1);
	if((fp = fopen(FIFO2,"r")) == NULL)
    {
        umask(0);
        mknod(FIFO2,S_IFIFO|06666,0);
    }
    else
        fclose(fp2);
	while(1)
	{
		if((fp = fopen(FIFO,"r")) == NULL)
		{
			printf("Open FIFO failed\n");
			exit(1);
		}
		if(fgets(readbuf,sizeof(readbuf),fp) != NULL)
		{
			printf("Recived string:%s \n",readbuf);
			fclose(fp);
			if(readbuf[0]=='1')
        	{
            	if((fp1=fopen(FIFO1,"w")) == NULL)
            	{
                	printf("Open FIFO1 failed.\n");
               		exit(1);
            	}
            	if(fputs("client1 received",fp1) == EOF)
            	{
                	printf("Write to PRIFIFO1 failed.\n");
                	exit(1);
            	}
            	fclose(fp1);
        	}
        	else if(readbuf[0]=='2')
        	{
            	if((fp2=fopen(FIFO2,"w")) == NULL)
            	{
                	printf("Open PRIFIFO2 failed.\n");
                	exit(1);
            	}
            	if(fputs("client2 received",fp2) == EOF)
           		{
                	printf("Write to PRIFIFO2 failed.\n");
                	exit(1);
            	}
            	fclose(fp2);
			}
		}
		else
		{
			if(ferror(fp))
			{
				printf("Read PUBFIFO failed.\n");
				exit(1);
			}
		}
	}
}
